const router = require("koa-router")();
const multer = require("@koa/multer");

const axios = require("axios");
const AK = "imsmA7O8WtX193NSfCdDolhp";
const SK = "6Y9XEjQFGX81nv5ClpniD6ZbEDG2nOTS";

router.post("/orc/upload/image", async (ctx) => {
  const file = ctx.request.files.file;
  const { filepath, originalFilename } = file;
  // 链接百度


  async function main() {
    var options = {
      method: "POST",
      url:
        "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" +
        (await getAccessToken()),
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        Accept: "application/json",
      },
      // image 可以通过 getFileContentAsBase64("C:\fakepath\身份证.png") 方法获取,
      data: {
        id_card_side: "front",
        image: getFileContentAsBase64(filepath),
        detect_ps: "false",
        detect_risk: "false",
        detect_quality: "false",
        detect_photo: "false",
        detect_card: "false",
        detect_direction: "false",
      },
    };

    return axios(options)
  }

  /**
   * 使用 AK，SK 生成鉴权签名（Access Token）
   * @return string 鉴权签名信息（Access Token）
   */
  function getAccessToken() {
    let options = {
      method: "POST",
      url:
        "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" +
        AK +
        "&client_secret=" +
        SK,
    };
    return new Promise((resolve, reject) => {
      axios(options)
        .then((res) => {
          resolve(res.data.access_token);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 获取文件base64编码
   * @param string  path 文件路径
   * @return string base64编码信息，不带文件头
   */
  function getFileContentAsBase64(path) {
    const fs = require("fs");
    try {
      return fs.readFileSync(path, { encoding: "base64" });
    } catch (err) {
      throw new Error(err);
    }
  }

  const resp =  await main() ;
  ctx.body = {
    code: 200,
    message: '识别成功',
    data: {
      name: resp.data.words_result["姓名"].words,
      code: resp.data.words_result["公民身份号码"].words
    }
  
  }
  // console.log(resp.data.words_result["姓名"].words)
  // console.log(resp.data.words_result["公民身份号码"].words)
});

module.exports = router;
